<template>
  <div class="login-page">
    <!-- 网页大标题 -->
    <SvgTitle />
    <div class="main-title">
      <p>以AI寻爱，用智慧拯救每一个家庭</p>
    </div>

    <!-- 表单容器 -->
    <div class="wrapper">
      <!-- 登录表单 -->
      <form v-if="!isForgotPassword && !isSignup" @submit.prevent="Login">
        <h1>登录</h1>
        <div v-if="!isEmailLogin">
          <!-- 用户名和密码登录 -->
          <div class="input-box">
            <input v-model="loginForm.accountNo" type="text" required />
            <label>用户名</label>
          </div>
          <div class="input-box">
            <input v-model="loginForm.accountPassword" :type="showPassword ? 'text' : 'password'" required/>
            <label>密码</label>
            <el-icon class="toggle-password" @click="showPassword = !showPassword">
              <ShowPasswordIcon v-if="showPassword" />
              <Hide v-else />
            </el-icon>
          </div>
        </div>
        <div v-else>
          <!-- 邮箱登录 -->
          <div class="input-box">
            <input v-model="loginForm.mail" type="text" required/>
            <label>邮箱</label>
          </div>
          <!-- 引入验证码组件 -->
          <Captcha
              type="type2"
              :mail="loginForm.mail"
              :account-no="loginForm.accountNo"
              v-model="loginForm.code"
              :sendVerificationCodeCallback="sendVerificationCode"
          />
        </div>

        <!-- 登录方式切换链接 -->
        <div class="row">
          <a @click="switchToForgotPassword" class="left-link">忘记密码？</a>
          <a @click="toggleLoginMethod" class="right-link">
            {{ isEmailLogin ? '用户名登录' : '邮箱登录' }}
          </a>
        </div>

        <!-- 登录按钮 -->
        <button type="submit" class="btn">登录</button>

        <!-- 账号注册链接 -->
        <div class="signup-link">
          <p>还没有账号？<a @click="switchToSignup">创建一个</a></p>
        </div>
      </form>

      <!-- 忘记密码表单 -->
      <form v-else-if="isForgotPassword">
        <template v-if="!isVerificationCorrect">
          <h1>忘记密码</h1>
          <div class="input-box">
            <input v-model="resetForm.accountNo" type="text" required/>
            <label>用户名</label>
          </div>
          <div class="input-box">
            <input v-model="resetForm.mail" type="text" required/>
            <label>邮箱</label>
          </div>
          <!-- 引入验证码组件 -->
          <Captcha
              type="type1"
              :account-no="resetForm.accountNo"
              :mail="resetForm.mail"
              v-model="resetForm.code"
              :sendVerificationCodeCallback="sendVerificationCode"
          />

          <button type="button" class="btn" @click="validateVerificationCode('reset')">
            验证验证码
          </button>
          <a @click="switchToLogin" class="back-link">返回登录</a>
        </template>

        <template v-else>
          <h1>重置密码</h1>
          <div class="input-box">
            <input v-model="resetForm.newPassword" type="password" required/>
            <label>新密码</label>
          </div>
          <div class="input-box">
            <input v-model="resetForm.confirmPassword" type="password" required/>
            <label>确认新密码</label>
          </div>
          <button type="button" class="btn" @click="resetPassword">重置密码</button>
        </template>
      </form>

      <!-- 创建账号表单 -->
      <form v-else @submit.prevent="signup">
        <h1>创建账号</h1>

        <template v-if="!isVerificationCorrect">
          <div class="input-box">
            <input v-model="signupForm.accountNo" type="text" required/>
            <label>用户名</label>
          </div>
          <div class="input-box">
            <input v-model="signupForm.mail" type="text" required/>
            <label>邮箱</label>
          </div>
          <!-- 引入验证码组件 -->
          <Captcha
              type="type3"
              :account-no="signupForm.accountNo"
              :mail="signupForm.mail"
              v-model="signupForm.code"
              :sendVerificationCodeCallback="sendVerificationCode"
          />
          <button type="button" class="btn" @click="validateCode">
            验证验证码
          </button>
        </template>

        <template v-else>
          <div class="input-box">
            <input v-model="signupForm.password" type="password" required/>
            <label>密码</label>
          </div>
          <div class="input-box">
            <input v-model="signupForm.confirmPassword" type="password" required/>
            <label>确认密码</label>
          </div>
          <button type="submit" class="btn">注册</button>
        </template>

        <a @click="switchToLogin" class="back-link">返回登录</a>
      </form>
    </div>
  </div>
</template>

<script lang="ts">
import router from "@/router";
import {defineComponent, reactive, ref} from "vue";
import Captcha from "./Captcha.vue";
import request from "@/utils/request.ts";
import SvgTitle from '@/components/Login/SvgTitle.vue'; // 引入标题组件
import { View as ShowPasswordIcon, Hide } from '@element-plus/icons-vue'; // 引入 Element Plus 图标

export default defineComponent({
  name: "LoginPage", // 修改为多单词组件名
  components: {
    SvgTitle,
    Captcha, // 注册时使用的验证码组件
    ShowPasswordIcon, // 使用新名称
    Hide, // 隐藏密码的图标组件
  },
  setup() {
    // 登录相关状态
    const isEmailLogin = ref(false); // 是否为邮箱登录
    const isForgotPassword = ref(false); // 是否为忘记密码页面
    const isSignup = ref(false); // 是否为注册页面
    const isVerificationCorrect = ref(false); // 验证码是否正确
    const showPassword = ref(false);

    // 表单数据
    const loginForm = reactive({
      accountNo: "",
      accountPassword: "",
      mail: "",
      code: "",
    });

    const resetForm = reactive({
      accountNo: "",
      mail: "",
      code: "",
      newPassword: "",
      confirmPassword: "",
    });

    const signupForm = reactive({
      accountNo: "",
      mail: "",
      code: "",
      password: "",
      confirmPassword: "",
    });

    const sendVerificationCode = async (email: string) => {
      console.log(`发送验证码到：${email}`);
      // 在此模拟验证码发送，实际应用中需要调用后端接口发送验证码
      return new Promise((resolve) => {
        setTimeout(() => {
          console.log("验证码已发送");
          resolve("验证码发送成功");
        }, 1000);
      });
    };

    // 切换到忘记密码页面
    const switchToForgotPassword = () => {
      isForgotPassword.value = true;
      isSignup.value = false;
    };

    // 切换到注册页面
    const switchToSignup = () => {
      isSignup.value = true;
      isForgotPassword.value = false;
    };

    // 切换到登录页面
    const switchToLogin = () => {
      isSignup.value = false;
      isForgotPassword.value = false;
      isVerificationCorrect.value = false;
    };

    // 切换登录方式
    const toggleLoginMethod = () => {
      isEmailLogin.value = !isEmailLogin.value;
      loginForm.mail = "";
      loginForm.accountNo = "";
      loginForm.code = "";
      loginForm.accountPassword = "";
    };

    // 登录
    const Login = () => {
      // 账号密码登陆
      if (loginForm.mail === "") {
        // 简单的前端验证
        if (loginForm.accountNo && loginForm.accountPassword) {
          // 验证管理员账号
          if (loginForm.accountNo === 'admin' && loginForm.accountPassword === '123456') {
            // 模拟登录成功
            const mockUserData = {
              accountNo: loginForm.accountNo,
              name: "管理员",
              role: "admin"
            };
            localStorage.setItem("user", JSON.stringify(mockUserData));
            localStorage.setItem("token", loginForm.accountNo);
            // 获取重定向地址或默认跳转到首页
            const redirect = router.currentRoute.value.query.redirect as string || '/';
            router.push(redirect);
            // 清空表单
            loginForm.mail = ""
            loginForm.accountNo = ""
            loginForm.code = ""
            loginForm.accountPassword = ""
          } else {
            alert("账号或密码错误！")
          }
        } else {
          alert("请输入账号和密码！")
        }
      } else {
        // 邮箱登陆
        if (loginForm.mail && loginForm.code) {
          // 模拟登录成功
          const mockUserData = {
            accountNo: loginForm.mail,
            name: "测试用户",
            role: "user"
          };
          localStorage.setItem("user", JSON.stringify(mockUserData));
          localStorage.setItem("token", loginForm.mail);
          // 获取重定向地址或默认跳转到首页
          const redirect = router.currentRoute.value.query.redirect as string || '/';
          router.push(redirect);
          // 清空表单
          loginForm.mail = ""
          loginForm.accountNo = ""
          loginForm.code = ""
          loginForm.accountPassword = ""
        } else {
          alert("请输入邮箱和验证码！")
        }
      }
    };


    // 忘记密码验证验证码是否正确
    const validateVerificationCode = (type: string) => {
      request.post("/account/verifyCode", resetForm).then(res => {
        if (res.data.code === '200') {
          isVerificationCorrect.value = true;
        } else {
          isVerificationCorrect.value = false;
          alert("验证码错误！");
        }
      });
    };

    // 注册时验证邮箱验证码
    const validateCode = () => {
      request.post("/account/verifyCode", signupForm).then(res => {
        if (res.data.code === '200') {
          isVerificationCorrect.value = true;
        } else {
          alert("验证码错误！");
        }
      });
    };

    // 重置密码
    const resetPassword = () => {
      if (!isVerificationCorrect.value) {
        alert("请先验证验证码！");
        return;
      }
      if (resetForm.newPassword !== resetForm.confirmPassword) {
        alert("两次输入的密码不一致！");
        return;
      } else {
        request.post("/account/rePwd", resetForm).then(res => {
          if (res.data.code === '200') {
            alert("密码重置成功！");
            switchToLogin();
          }
        });
      }
    };

    // 注册
    const signup = () => {
      if (signupForm.password !== signupForm.confirmPassword) {
        alert("两次输入的密码不一致！");
      } else {
        request.post("/account/signup", signupForm).then(res => {
          if (res.data.code === '200') {
            alert("注册成功！");
            switchToLogin();
          } else {
            alert("账号已存在！请登录！");
            switchToLogin();
          }
        });
      }
    };

    return {
      loginForm,
      resetForm,
      signupForm,
      switchToForgotPassword,
      switchToSignup,
      switchToLogin,
      toggleLoginMethod,
      isEmailLogin,
      isForgotPassword,
      isSignup,
      isVerificationCorrect,
      Login,
      validateVerificationCode,
      resetPassword,
      signup,
      sendVerificationCode,
      validateCode,
      showPassword,
      ShowPasswordIcon,
      Hide,
    };
  },
});
</script>

<style scoped>
/* 页面全局样式 */
* {
  font-family: "Poppins", sans-serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 登录页面背景设置 */
.login-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: url("/img/背景.png") no-repeat center center;
  background-size: cover;
  padding: 20px;

  /* &::before {
    content: "";
    position: absolute;
    top: 8%;
    left: 47%;
    width: 70px;
    height: 90px;
    background-image: url("https://user-images.githubusercontent.com/8554143/207571012-c2141cfb-4671-438d-bbf3-437838dd3d1a.gif");
    background-size: cover;
    background-position: -30px 0;
    mix-blend-mode: multiply;
    filter: contrast(2);
  } */
}

/* 网页大标题样式 */
.main-title {
  text-align: center;
  margin-bottom: 20px;
  animation: fadeIn 3s;
}

.main-title p {
  font-size: 34px;
  color: #fff;
}

/* 动效 */
@keyframes fadeIn {
  0% {
    opacity: 0;
    transform: translateY(-20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 表单容器 */
.wrapper {
  width: 600px;
  padding: 20px;
  backdrop-filter: blur(8px) brightness(90%);
  background-color: rgba(255, 255, 255, 0.28);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.4);
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.wrapper:hover {
  box-shadow: 0 0 15px rgba(255, 77, 77, 0.8),
  0 0 30px rgba(255, 0, 0, 0.6),
  0 0 45px rgba(204, 0, 0, 0.4);
  transition: box-shadow 0.3s ease-in-out;
}

/* 表单标题 */
.wrapper h1 {
  font-size: 36px;
  color: #fff;
  text-align: center;
  margin-bottom: 20px;
}

/* 输入框通用样式 */
.input-box {
  position: relative;
  width: 250px;
  margin-bottom: 25px;
  border-bottom: 2px solid #fff;
}

.input-box input {
  width: 100%; /* 输入框宽度统一 */
  height: 40px; /* 输入框高度统一 */
  background: transparent;
  outline: none;
  border: none;
  font-size: 22px;
  color: #fff;
  padding: 0 10px;
}

.input-box label {
  position: absolute;
  top: 50%;
  left: 10px;
  transform: translateY(-50%);
  font-size: 16px;
  color: #fff;
  pointer-events: none;
  transition: 0.3s;
}

/* 激活状态或输入有值时文字上浮 */
.input-box input:focus ~ label,
.input-box input:valid ~ label {
  top: -10px;
  font-size: 14px;
  color: #ccc;
}

/* 忘记密码和邮箱登录 */
.row {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.row a {
  color: #fff;
  text-decoration: none;
  cursor: pointer;
}

/* 登录按钮 */
.btn {
  width: 100%;
  height: 40px;
  background: linear-gradient(90deg, #FF4D4D, #CC0000);
  border: none;
  border-radius: 20px;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  cursor: pointer;
  margin-top: 10px;
  transition: background 0.3s;
}

.btn:hover {
  background: linear-gradient(90deg, #FF6666, #FF0000);
}

/* 注册链接 */
.signup-link {
  font-size: 16px;
  color: #fff;
  text-align: center;
  margin-top: 15px;
  cursor: pointer;  /* 添加悬浮指针样式 */
}

.signup-link:hover {
  text-decoration: underline; /* 保留下划线效果 */
}

/* 返回链接 */
.back-link {
  text-align: center;
  font-size: 16px;
  color: #fff;
  cursor: pointer;  /* 添加悬浮指针样式 */
}

.back-link:hover {
  text-decoration: underline; /* 保留下划线效果 */
}

/* 密码显示/隐藏图标样式 */
.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  font-size: 18px;
}

</style>
